/*Copyright ©2015 TommyLemon(https://github.com/TommyLemon)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/

package bjx.com.siji.zxing.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.Result;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import bjx.com.siji.R;
import bjx.com.siji.application.App;
import bjx.com.siji.engine.Engine;
import bjx.com.siji.utils.LogsUtil;
import bjx.com.siji.zxing.view.ViewfinderView;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 扫描二维码Activity
 *
 * @author Lemon
 * @use toActivity(ScanActivity.createIntent ( ...));
 */
public class ScanActivity extends CaptureActivity implements ActivityPresenter, OnClickListener {
    public static final String TAG = "ScanActivity";

    private int fromType = 0;

    private int flag = 0;
    protected Engine mEngine;
    protected App mApp;

    /**
     * 启动这个Activity的Intent
     *
     * @param context
     * @return
     */
    public static Intent createIntent(Context context) {
        return new Intent(context, ScanActivity.class);
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.scan_activity);
        mApp = App.getInstance();
        mEngine = mApp.getEngine();
        init(this, (SurfaceView) findViewById(R.id.svCameraScan), (ViewfinderView) findViewById(R.id.vfvCameraScan));

        setScanMode(1);

        initView();
        initData();
        initEvent();

    }

    @Override
    public void initView() {//必须调用
        TextView titleTextView = (TextView) findViewById(R.id.title);
        titleTextView.setText("扫一扫");
        findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                (ScanActivity.this).onBackPressed();
            }
        });
    }

    @Override
    public void initData() {//必须调用

    }

    @Override
    public void handleDecode(Result result, Bitmap barcode) {
        super.handleDecode(result, barcode);
        String resultString = result.getText();
        if (resultString.equals("")) {
            Toast.makeText(ScanActivity.this, "扫描失败!", Toast.LENGTH_SHORT).show();
            restartPreviewAndDecode();
        } else {

             LogsUtil.order("扫描结果"+resultString);
//            if (resultString.length() > 30) {
//                resultString = resultString.substring(0, 30);
//            }


             mEngine.getPaCard(resultString,"").enqueue(new Callback<ResponseBody>() {

                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    try {
                        String str = response.body().string();
                        LogsUtil.order("扫描成功" + str);

                        JSONObject jo = new JSONObject(str);
                        int status = jo.getInt("status");
                        String msg = jo.getString("kilo");
                        String cardId = jo.getString("card");
                        String useStatus = jo.getString("used");

                        if (status == 200) {
                            LogsUtil.order("公里数" + msg);


                            Intent resultIntent = new Intent();
                            Bundle bundle = new Bundle();

                            if ("0".equals(useStatus)){//未使用
                                bundle.putString("result", msg);
                            }else {
                                bundle.putString("result", "0");
                            }
                            bundle.putString("result", msg);
                            bundle.putString("card", cardId);

                            resultIntent.putExtras(bundle);

                            ScanActivity.this.setResult(RESULT_OK, resultIntent);
                            ScanActivity.this.finish();


                        } else if (status == 201) {

                        } else if (status == 100) {

                        } else {
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                }
            });

        }
    }

    @Override
    public void initEvent() {//必须调用
         findViewById(R.id.ivCameraScanLight).setOnClickListener(this);
    }


    @Override
    public void onReturnClick(View v) {
        if (fromType != 2 || flag > 2) {
            finish();
        } else {
            flag++;
            Toast.makeText(ScanActivity.this, "请认证二维码(" + (3 - flag) + ")", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onForwardClick(View v) {
        //		CommonUtil.toActivity(context, QRCodeActivity.createIntent(context, 1));

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivCameraScanLight:
                switchLight(!isOn());
                break;
            default:
                break;
        }
    }


    @Override
    public boolean isAlive() {
        return false;
    }

    @Override
    public boolean isRunning() {
        return false;
    }

}